package rbac_api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
	"golang.org/x/crypto/bcrypt"
)

type userCreateReq struct {
	Email    string `p:"email"`
	Tel      string `p:"tel"`
	Name     string `p:"name"`
	Password string `p:"password"`
}

type userCreateRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type userCreateOrm struct {
	Email    string `orm:"email"`
	Tel      string `orm:"tel"`
	Name     string `orm:"name"`
	Password string `orm:"password"`
}

func (a *userApi) Create(r *ghttp.Request) {
	//输入参数接收
	var req *userCreateReq
	if err := r.Parse(&req); err != nil {
		r.Response.WriteJsonExit(userCreateRes{
			Code: 0,
			Msg:  err.Error(),
		})
	}
	//输入参数校验
	rules := map[string]string{
		"email":    "required|length:1,16",
		"name":     "required|length:1,16",
		"tel":      "required|length:1,16",
		"password": "required|length:1,16",
	}
	msgs := map[string]interface{}{
		"email": map[string]string{
			"required": "邮箱不能为空",
			"length":   "邮箱长度太长",
		},
		"name": map[string]string{
			"required": "姓名不能为空",
			"length":   "姓名长度太长",
		},
		"tel": map[string]string{
			"required": "电话不能为空",
			"length":   "电话长度太长",
		},
		"password": map[string]string{
			"required": "密码不能为空",
			"length":   "密码长度太长",
		},
	}
	if e := gvalid.CheckMap(req, rules, msgs); e != nil {
		r.Response.WriteJsonExit(userCreateRes{
			Code: 0,
			Msg:  e.String(),
		})
	}

	//验证唯一性
	m0, err := g.DB().Model("user").Where("email=?", req.Email).One()
	if err == nil {
		if !m0.IsEmpty() {
			r.Response.WriteJsonExit(userCreateRes{
				Code: 0,
				Msg:  "邮箱已存在",
			})
		}
	}

	//orm参数转换
	var userCreateOrm userCreateOrm
	userCreateOrm.Tel = req.Tel
	userCreateOrm.Email = req.Email
	userCreateOrm.Name = req.Name
	//密码加密
	hash, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	userCreateOrm.Password = string(hash[:])
	//插入数据
	m, err := g.DB().Model("user").Data(userCreateOrm).Insert()
	lastInsertId, err := m.LastInsertId()

	//输出结果
	if err != nil {
		r.Response.WriteJsonExit(userCreateRes{
			Code: 0,
		})
	}

	r.Response.WriteJsonExit(userCreateRes{
		Code: 1,
		Data: lastInsertId,
	})
}
